package com.terrace.core.mybatis.plugin.pagination.sqlsource;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;

import com.terrace.core.mybatis.entity.Signal;
import com.terrace.core.mybatis.plugin.pagination.Constant;
import com.terrace.core.mybatis.plugin.pagination.PaginationHandler;
import com.terrace.core.mybatis.plugin.pagination.parser.Parser;

/**
 * 分页
 * @author jiangyg
 *
 */
public abstract class PaginationSqlSource implements SqlSource, Constant {
	
	/**
	 * 线程局部SQL解析器
	 */
	protected static final ThreadLocal<Parser> THREAD_LOCAL_PARSER = new ThreadLocal<Parser>();
	
	/**
	 * 设置线程局部解析器
	 * @param parser
	 */
	public static void setParser(Parser parser) {
		THREAD_LOCAL_PARSER.set(parser);
	}
	
	/**
	 * 移除线程局部解析器
	 */
	public static void removeParser() {
		THREAD_LOCAL_PARSER.remove();
	}
	
	/**
     * 获取正常的BoundSql
     *
     * @param parameterObject
     * @return
     */
    protected abstract BoundSql getDefaultBoundSql(Object parameterObject);
	
	/**
	 * 获取分页统计BoundSql
	 * @param parameterObject
	 * @return
	 */
	protected abstract BoundSql getCountBoundSql(Object parameterObject);
	
	/**
	 * 获取分页BoundSql
	 * @param parameterObject
	 * @return
	 */
	protected abstract BoundSql getPaginationBoundSql(Object parameterObject);

	/**
	 * 获取未经处理的BoundSql
	 */
	@Override
	public BoundSql getBoundSql(Object parameterObject) {
		BoundSql boundSql;
		Signal signal = PaginationHandler.getSignal();
		switch (signal) {
			case COUNT:
				boundSql = this.getCountBoundSql(parameterObject);
				break;
			case PAGINATION:
				boundSql = this.getPaginationBoundSql(parameterObject);
				break;
			default:
				boundSql = this.getDefaultBoundSql(parameterObject);
				break;
		}
		return boundSql;
	}

}
